<?php

namespace app\admin\controller;

use app\admin\library\Auth;
use app\common\controller\Backend;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use think\Db;
use think\db\exception\BindParamException;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 账号管理
 *
 * @icon fa fa-circle-o
 */
class Accounten extends Backend
{

    /**
     * Accounten模型对象
     * @var \app\admin\model\Accounten
     */
    protected $model = null;

    protected $selectpageFields = "id,name,zhanghao,address,mobile";
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Accounten;
        $this->view->assign("accTypeList", $this->model->getAccTypeList());
        $this->view->assign("isYajinList", $this->model->getIsYajinList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','acc_type','shouli_date','zhanghao','password','zhaoshu','stop_date','name','mobile','address','card','is_yajin','user_date','guishu','zidan','remark','createtime','updatetime']);
                
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        $new_str = '';
        if($params['acc_type']){
            $new_str .= "运营商:".$this->model->getAccTypeList2($params['acc_type']).',';
        }
        if($params['zhanghao']){
            $new_str .= "账号:".$params['zhanghao'].',';
        }
        if($params['password'] ){
            $new_str .= "密码:".$params['password'].',';
        }
        if($params['zhaoshu']){
            $new_str .= "兆数:".$params['zhaoshu'].',';
        }
        if($params['stop_date']){
            $new_str .= "账号停用日期:".$params['stop_date'].',';
        }
        if($params['name']){
            $new_str .= "用户姓名:".$params['name'].',';
        }
        if($params['mobile']){
            $new_str .= "联系电话:".$params['mobile'].',';
        }
        if($params['address']){
            $new_str .= "现居地址:".$params['address'].',';
        }
        if($params['card']){
            $new_str .= "身份证号:".$params['card'].',';
        }
        if($params['user_date']){
            $new_str .= "使用人到期时间:".$params['user_date'].',';
        }
        if($params['guishu']){
            $new_str .= "账号归属:".$params['guishu'].',';
        }
        if($params['zidan']){
            $new_str .= "子单:".$params['zidan'].',';
        }
        $n = $params['is_yajin']?'是':'否';
        $new_str .= "光猫押金:".$n.',';
        $loginuser = $this->auth->getUserInfo();
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            $log = [
                'account_id' => $this->model->id,
                'zhanghao' => $params['zhanghao'],
                'opt_user' =>$loginuser['username'],
                'new_content' =>trim($new_str,','),
            ];
            // var_dump($log);die();
            \app\admin\model\Accountlog::create($log);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }


    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $loginuser = $this->auth->getUserInfo();

        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        $old_str = '';
        $new_str = '';
       /* var_dump($params);
        var_dump($row);*/
        if($params['zhanghao'] != $row['zhanghao']){
            $old_str .= "旧账号:".$row['zhanghao'].',';
            $new_str .= "新账号:".$params['zhanghao'].',';
        }
        if($params['acc_type'] != $row['acc_type']){
            $old_str .= "旧运营商:".$this->model->getAccTypeList2($row['acc_type']).',';
            $new_str .= "新运营商:".$this->model->getAccTypeList2($params['acc_type']).',';
        }
        if($params['password'] != $row['password']){
            $old_str .= "旧密码:".$row['password'].',';
            $new_str .= "新密码:".$params['password'].',';
        }
        if($params['zhaoshu'] != $row['zhaoshu']){
            $old_str .= "兆数旧数据:".$row['zhaoshu'].',';
            $new_str .= "新兆新数据:".$params['zhaoshu'].',';
        }
        if($params['stop_date'] != $row['stop_date']){
            $old_str .= "旧账号停用日期:".$row['stop_date'].',';
            $new_str .= "新账号停用日期:".$params['stop_date'].',';
        }
        if($params['name'] != $row['name']){
            $old_str .= "旧用户姓名:".$row['name'].',';
            $new_str .= "新用户姓名:".$params['name'].',';
        }
        if($params['mobile'] != $row['mobile']){
            $old_str .= "旧联系电话:".$row['mobile'].',';
            $new_str .= "新联系电话:".$params['mobile'].',';
        }
        if($params['address'] != $row['address']){
            $old_str .= "旧现居地址:".$row['address'].',';
            $new_str .= "新现居地址:".$params['address'].',';
        }
        if($params['card'] != $row['card']){
            $old_str .= "旧身份证号:".$row['card'].',';
            $new_str .= "新身份证号:".$params['card'].',';
        }
        if($params['user_date'] != $row['user_date']){
            $old_str .= "旧使用人到期时间:".$row['user_date'].',';
            $new_str .= "新使用人到期时间:".$params['user_date'].',';
        }
        if($params['guishu'] != $row['guishu']){
            $old_str .= "旧账号归属:".$row['guishu'].',';
            $new_str .= "新账号归属:".$params['guishu'].',';
        }
        if($params['zidan'] != $row['zidan']){
            $old_str .= "旧子单:".$row['zidan'].',';
            $new_str .= "新子单:".$params['zidan'].',';
        }
        if($params['is_yajin'] != $row['is_yajin']){
            $o = $row['is_yajin']?'是':'否';
            $n = $params['is_yajin']?'是':'否';
            $old_str .= "旧光猫押金:".$o.',';
            $new_str .= "新光猫押金:".$n.',';
        }


        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);

            $log = [
                'account_id' => $row['id'],
                'zhanghao' => $params['zhanghao'],
                'opt_user' =>$loginuser['username'],
                'old_content' => trim($old_str,','),
                'new_content' =>trim($new_str,','),
            ];
           // var_dump($log);die();
            \app\admin\model\Accountlog::create($log);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 删除
     *
     * @param $ids
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();
        $loginuser = $this->auth->getUserInfo();

        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                $log = [
                    'account_id' => $item['id'],
                    'zhanghao' => $item['zhanghao'],
                    'opt_user' =>$loginuser['username'],
                    'old_content' =>json_encode($item,JSON_UNESCAPED_UNICODE),
                    'new_content' =>'账号：'.$item['zhanghao'].'被删除',
                    //'remark'=> json_encode($item,JSON_UNESCAPED_UNICODE)
                ];
                // var_dump($log);die();
                \app\admin\model\Accountlog::create($log);
                $count += $item->delete();
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }

    public function userclear($ids)
    {
        $loginuser = $this->auth->getUserInfo();

        $row = $this->model->get($ids);
        if(empty($row['name'])){
            $this->error('已经清除');
        }
        $old_str = '';
        if($row['name']){
            $old_str .= "用户姓名:".$row['name'].',';
        }
        if($row['mobile']){
            $old_str .= "联系电话:".$row['mobile'].',';
        }
        if($row['address']){
            $old_str .= "现居地址:".$row['address'].',';
        }
        if($row['card']){
            $old_str .= "身份证号:".$row['card'].',';
        }
        $log = [
            'account_id' => $ids,
            'zhanghao' => $row['zhanghao'],
            'opt_user' =>$loginuser['username'],
            'old_content' => trim($old_str,','),
            'new_content' =>'清空用户资料',
        ];
        $row->name = '';
        $row->mobile = '';
        $row->address = '';
        $row->card = '';
        $row->is_yajin = 0;
        $row->save();
        // var_dump($log);die();
        \app\admin\model\Accountlog::create($log);
        $this->success('操作成功');
    }


    /**
     * 导入
     *
     * @return void
     * @throws PDOException
     * @throws BindParamException
     */
    public function import()
    {
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'xls') {
            $reader = new Xls();
            $reader->setReadDataOnly(true);
        } else {
            $reader = new Xlsx();
            $reader->setReadDataOnly(true);
        }

        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

        $table = $this->model->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
        foreach ($list as $k => $v) {
            if ($importHeadType == 'comment') {
                $v['COLUMN_COMMENT'] = explode(':', $v['COLUMN_COMMENT'])[0]; //字段备注有:时截取
                $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
            } else {
                $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
            }
        }

        //加载文件
        $insert = [];
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            $fields = [];
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $fields[] = $val;
                }
            }

            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $values[] = is_null($val) ? '' : $val;
                }
                $row = [];
                $temp = array_combine($fields, $values);

                foreach ($temp as $k => $v) {
                    if (isset($fieldArr[$k]) && $k !== '') {
                        if(empty($row[$fieldArr[$k]]) && isset($row['name'])){
                            //break;
                        }
                        $row[$fieldArr[$k]] = $v;
                        //echo $fieldArr[$k].'<br/>';

                    }
                }

                if ($row) {
                    $insert[] = $row;
                }
            }
            $insert2 = [];
            foreach ($insert as $k1 => $v1) {

                if(!empty($v1['stop_date'])){
                    $v1['stop_date'] = excelDateToPhp($v1['stop_date']);
                    if(!empty($v1['user_date'])){
                        $v1['user_date'] = excelDateToPhp($v1['user_date']);
                    }
                    $zhichu = array_search($v1['acc_type'],  $this->model->getAccTypeList());
                    $v1['acc_type'] = $zhichu?$zhichu:0;
                    $is_yajin = $v1['is_yajin'] == '是'?1:0;
                    $v1['is_yajin']= $is_yajin;
                    $v1['is_daoru']= 1;
                    $insert2[$k1] = $v1;
                }else{
                    break;
                }
            }
            $insert = $insert2;
           // print_r($insert);die();
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
        if (!$insert) {
            $this->error(__('No rows were updated'));
        }

        try {
            //是否包含admin_id字段
            $has_admin_id = false;
            foreach ($fieldArr as $name => $key) {
                if ($key == 'admin_id') {
                    $has_admin_id = true;
                    break;
                }
            }
            if ($has_admin_id) {
                $auth = Auth::instance();
                foreach ($insert as &$val) {
                    if (!isset($val['admin_id']) || empty($val['admin_id'])) {
                        $val['admin_id'] = $auth->isLogin() ? $auth->id : 0;
                    }
                }
            }
            $this->model->saveAll($insert);
        } catch (PDOException $exception) {
            $msg = $exception->getMessage();
            if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
                $msg = "导入失败，包含【{$matches[1]}】的记录已存在";
            };
            $this->error($msg);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success();
    }

}